const { ref, onMounted } = Vue

let template = {
  name: 'book_type',
  template: '',
  setup() {
    const bookTypeList = ref([])
    const loading = ref(false)
    const addBookTypeDialogVisible = ref(false)
    const bookType = ref('')

    async function getAll() {
      loading.value = true
      let res = await Http('/book_type/all')

      if (res && res.code === 200) {
        bookTypeList.value = res.data
      } else {
        ElMessage.error('获取失败')
      }
      loading.value = false
    }
    async function addBookType() {
      let res = await Http.post('/book_type/add', { type: bookType.value })

      if (res && res.code === 200) {
        bookType.value = ''
        addBookTypeDialogVisible.value = false
        getAll()
        ElMessage.success(res.message)
      } else {
        ElMessage.error(res.message)
      }
    }
    async function deleteBookType(id) {
      let res = await Http.post('/book_type/delete', { id })

      if (res && res.code === 200) {
        getAll()
        ElMessage.success(res.message)
      } else {
        ElMessage.error(res.message)
      }
    }

    onMounted(() => {
      getAll()
    })

    return {
      bookTypeList,
      loading,
      bookType,
      addBookTypeDialogVisible,
      getAll,
      addBookType,
      deleteBookType,
    }
  },
}

export default {
  async load() {
    const { name } = template

    return fetch(`${config.RP}/html/route/${name}/${name}.html`)
      .then((res) => res.text())
      .then((html) => {
        template.template = html
        window.app.component(name, template)
      })
  },
}
